const express = require('express');
const router = express.Router();
const axios = require('axios');
const User = require('../models/User');
const db = require('../config/database');




// 获取用户完整信息接口 - 下单者/代拿者通用个人资料
router.get('/profile/:id', async (req, res) => {
    try {
        const userId = req.params.id;
        console.log(`👤 获取用户信息，用户ID: ${userId}`);

        // 获取基础用户信息
        const [users] = await db.execute(
            'SELECT * FROM users WHERE id = ?',
            [userId]
        );

        if (users.length === 0) {
            return res.status(404).json({
                success: false,
                message: '用户不存在'
            });
        }

        const user = users[0];

        // 获取下单者信息
        const [orderUsers] = await db.execute(
            'SELECT * FROM order_users WHERE user_id = ?',
            [userId]
        );

        // 获取代拿员信息
        const [courierUsers] = await db.execute(
            'SELECT * FROM courier_users WHERE user_id = ?',
            [userId]
        );

        res.json({
            success: true,
            data: {
                user: {
                    id: user.id,
                    openid: user.openid,
                    nickname: user.nickname,
                    avatar_url: user.avatar_url,
                    phone: user.phone,
                    email: user.email || null,
                    email_verified: user.email_verified ?? null,
                    created_at: user.created_at
                },
                order_user: orderUsers.length > 0 ? orderUsers[0] : null,
                courier_user: courierUsers.length > 0 ? courierUsers[0] : null
            }
        });
    } catch (error) {
        console.error('获取用户信息错误:', error);
        res.status(500).json({
            success: false,
            message: '获取用户信息失败',
            error: process.env.NODE_ENV === 'development' ? error.message : undefined
        });
    }
});

// 更新个人资料（Web 端下单者“个人信息”页面使用）
router.put('/profile/:id', async (req, res) => {
    try {
        const userId = req.params.id;
        const {
            nickname,
            phone,
            email,
            avatar_url,
            college,
            major,
            student_id,
            dorm_building,
            dorm_room,
            service_range,
            service_time
        } = req.body || {};

        if (!nickname && !phone && !email && !avatar_url && !college && !major && !student_id && !dorm_building && !dorm_room && service_range === undefined && service_time === undefined) {
            return res.json({
                success: false,
                message: '没有可更新的字段'
            });
        }

        // 1. 更新 users 表中的基础信息
        if (nickname || phone || email || avatar_url) {
            const userUpdates = [];
            const userParams = [];

            if (nickname !== undefined) {
                const trimmed = String(nickname).trim();
                if (!trimmed) {
                    return res.json({ success: false, message: '昵称不能为空' });
                }
                if (trimmed.length < 2 || trimmed.length > 20) {
                    return res.json({ success: false, message: '昵称长度必须在2-20个字符之间' });
                }
                userUpdates.push('nickname = ?');
                userParams.push(trimmed);
            }

            if (phone !== undefined) {
                userUpdates.push('phone = ?');
                userParams.push(phone);
            }

            if (email !== undefined) {
                userUpdates.push('email = ?');
                userParams.push(email);
            }

            if (avatar_url !== undefined) {
                userUpdates.push('avatar_url = ?');
                userParams.push(avatar_url);
            }

            if (userUpdates.length > 0) {
                userParams.push(userId);
                await db.execute(
                    `UPDATE users SET ${userUpdates.join(', ')} WHERE id = ?`,
                    userParams
                );
            }
        }

        // 2. 更新 order_users 表中的扩展信息（学院、专业、宿舍等）
        if (college || major || student_id || dorm_building || dorm_room) {
            // 确保存在下单者记录
            const orderUser = await findOrCreateOrderUser(userId);
            const orderUpdates = [];
            const orderParams = [];

            if (college !== undefined) {
                orderUpdates.push('college = ?');
                orderParams.push(college);
            }

            if (major !== undefined) {
                orderUpdates.push('major = ?');
                orderParams.push(major);
            }

            if (student_id !== undefined) {
                orderUpdates.push('student_id = ?');
                orderParams.push(student_id);
            }

            if (dorm_building !== undefined) {
                orderUpdates.push('dorm_building = ?');
                orderParams.push(dorm_building);
            }

            if (dorm_room !== undefined) {
                orderUpdates.push('dorm_room = ?');
                orderParams.push(dorm_room);
            }

            if (orderUpdates.length > 0) {
                orderParams.push(orderUser.id);
                await db.execute(
                    `UPDATE order_users SET ${orderUpdates.join(', ')} WHERE id = ?`,
                    orderParams
                );
            }
        }

        // 3. 更新 courier_users 表中的代拿员扩展信息（服务范围、常接单时间）
        if (service_range !== undefined || service_time !== undefined) {
            await ensureCourierServiceColumns();
            const [courierUsers] = await db.execute(
                'SELECT id FROM courier_users WHERE user_id = ? LIMIT 1',
                [userId]
            );

            if (courierUsers.length > 0) {
                const courierUpdates = [];
                const courierParams = [];

                if (service_range !== undefined) {
                    courierUpdates.push('service_range = ?');
                    courierParams.push(service_range);
                }

                if (service_time !== undefined) {
                    courierUpdates.push('service_time = ?');
                    courierParams.push(service_time);
                }

                if (courierUpdates.length > 0) {
                    courierParams.push(courierUsers[0].id);
                    await db.execute(
                        `UPDATE courier_users SET ${courierUpdates.join(', ')} WHERE id = ?`,
                        courierParams
                    );
                }
            }
        }

        res.json({
            success: true,
            message: '个人资料更新成功'
        });
    } catch (error) {
        console.error('❌ 更新个人资料失败:', error);
        res.status(500).json({
            success: false,
            message: '更新个人资料失败'
        });
    }
});

// 用户登录/注册接口
router.post('/login', async (req, res) => {
    const { openid, nickname, avatar_url, phone } = req.body;

    try {
        // 1. 查找或创建基础用户
        let user = await findOrCreateUser(openid, nickname, avatar_url, phone);

        // 2. 自动为用户创建下单者身份（如果不存在）
        let orderUser = await findOrCreateOrderUser(user.id);

        // 3. 检查用户是否有代拿员身份
        let courierUser = await findCourierUser(user.id);

        res.json({
            success: true,
            message: '登录成功',
            data: {
                user: {
                    id: user.id,
                    nickname: user.nickname,
                    avatar_url: user.avatar_url,
                    phone: user.phone
                },
                order_user: orderUser ? {
                    id: orderUser.id,
                    credit_score: orderUser.credit_score,
                    total_orders: orderUser.total_orders
                } : null,
                courier_user: courierUser ? {
                    id: courierUser.id,
                    student_id: courierUser.student_id,
                    credit_score: courierUser.credit_score,
                    status: courierUser.status,
                    total_orders: courierUser.total_orders
                } : null
            }
        });
    } catch (error) {
        console.error('登录错误:', error);
        res.status(500).json({
            success: false,
            message: '登录失败',
            error: error.message
        });
    }
});

// 申请成为代拿员接口
router.post('/apply-courier', async (req, res) => {
    const { user_id, student_id } = req.body;

    try {
        // 检查是否已经是代拿员
        const [existing] = await db.execute(
            'SELECT * FROM courier_users WHERE user_id = ?',
            [user_id]
        );

        if (existing.length > 0) {
            return res.json({
                success: true,
                message: '您已经是代拿员',
                data: existing[0]
            });
        }

        // 创建代拿员身份，设置初始信用分为100
        const [result] = await db.execute(
            'INSERT INTO courier_users (user_id, student_id, credit_score) VALUES (?, ?, 100)',
            [user_id, student_id]
        );

        res.json({
            success: true,
            message: '代拿员身份创建成功',
            data: {
                id: result.insertId,
                user_id,
                student_id,
                credit_score: 100,
                status: 0
            }
        });
    } catch (error) {
        console.error('申请代拿员错误:', error);
        res.status(500).json({
            success: false,
            message: '申请失败',
            error: error.message
        });
    }
});

// 辅助函数：查找或创建用户
async function findOrCreateUser(openid, nickname, avatar_url, phone) {
    let [users] = await db.execute(
        'SELECT * FROM users WHERE openid = ?',
        [openid]
    );

    if (users.length > 0) {
        return users[0];
    } else {
        // 创建新用户
        const [result] = await db.execute(
            'INSERT INTO users (openid, nickname, avatar_url, phone) VALUES (?, ?, ?, ?)',
            [openid, nickname, avatar_url, phone]
        );

        return {
            id: result.insertId,
            openid,
            nickname,
            avatar_url,
            phone
        };
    }
}

// 辅助函数：查找或创建下单者身份
async function findOrCreateOrderUser(userId) {
    let [orderUsers] = await db.execute(
        'SELECT * FROM order_users WHERE user_id = ?',
        [userId]
    );

    if (orderUsers.length > 0) {
        return orderUsers[0];
    } else {
        // 自动创建下单者身份
        const [result] = await db.execute(
            'INSERT INTO order_users (user_id) VALUES (?)',
            [userId]
        );

        return {
            id: result.insertId,
            user_id: userId,
            credit_score: 100
        };
    }
}

// 辅助函数：查找代拿员身份
async function findCourierUser(userId) {
    let [courierUsers] = await db.execute(
        'SELECT * FROM courier_users WHERE user_id = ?',
        [userId]
    );

    return courierUsers.length > 0 ? courierUsers[0] : null;
}



// 获取用户信息 - 新增接口
router.get('/:userId', async (req, res) => {
    try {
        const { userId } = req.params;
        console.log(`👤 获取用户信息，用户ID: ${userId}`);

        const [users] = await db.execute(
            'SELECT id, phone, nickname, avatar_url, created_at FROM users WHERE id = ?',
            [userId]
        );

        if (users.length === 0) {
            return res.json({
                success: false,
                message: '用户不存在'
            });
        }

        res.json({
            success: true,
            data: users[0]
        });

    } catch (error) {
        console.error('❌ 获取用户信息失败:', error);
        res.status(500).json({
            success: false,
            message: '获取用户信息失败'
        });
    }
});

// 检查手机号验证状态 - 新增接口
router.get('/check-phone', async (req, res) => {
    try {
        const { userId } = req.query;

        console.log(`📱 检查手机号验证状态，用户ID: ${userId}`);

        // 这里模拟手机号已验证
        // 实际项目中应该检查数据库中的验证状态
        res.json({
            success: true,
            data: {
                isVerified: true
            }
        });

    } catch (error) {
        console.error('❌ 检查手机号失败:', error);
        res.status(500).json({
            success: false,
            message: '检查失败'
        });
    }
});

// 获取用户信用分 - 新增接口
router.get('/credit/:userId', async (req, res) => {
    try {
        const { userId } = req.params;

        console.log(`⭐ 获取用户信用分，用户ID: ${userId}`);

        // 模拟信用分数据
        // 实际项目中应该从数据库查询
        res.json({
            success: true,
            data: {
                score: 100,
                trend: 'flat',
                change: 0
            }
        });

    } catch (error) {
        console.error('❌ 获取信用分失败:', error);
        res.status(500).json({
            success: false,
            message: '获取信用分失败'
        });
    }
});

// 获取下单者信用分 - 新增接口
router.get('/order-users/credit/:userId', async (req, res) => {
    try {
        const { userId } = req.params;

        console.log(`📦 获取下单者信用分，用户ID: ${userId}`);

        // 查询下单者信用分，返回值封顶 100
        const [orderUsers] = await db.execute(
            'SELECT LEAST(credit_score, 100) AS credit_score FROM order_users WHERE user_id = ?',
            [userId]
        );

        const creditScore = orderUsers.length > 0 ? orderUsers[0].credit_score : 100;

        res.json({
            success: true,
            data: {
                score: creditScore,
                trend: 'flat',
                change: 0
            }
        });

    } catch (error) {
        console.error('❌ 获取下单者信用分失败:', error);
        res.status(500).json({
            success: false,
            message: '获取信用分失败'
        });
    }
});

// 获取代拿员信用分 - 新增接口
router.get('/courier-users/credit/:userId', async (req, res) => {
    try {
        const { userId } = req.params;

        console.log(`🚴 获取代拿员信用分，用户ID: ${userId}`);

        // 查询代拿员信用分，返回值封顶 100
        const [courierUsers] = await db.execute(
            'SELECT LEAST(credit_score, 100) AS credit_score FROM courier_users WHERE user_id = ?',
            [userId]
        );

        const creditScore = courierUsers.length > 0 ? courierUsers[0].credit_score : 100;

        res.json({
            success: true,
            data: {
                score: creditScore,
                trend: 'flat',
                change: 0
            }
        });

    } catch (error) {
        console.error('❌ 获取代拿员信用分失败:', error);
        res.status(500).json({
            success: false,
            message: '获取信用分失败'
        });
    }
});

// 代拿员评价下单者信用分 - 新增接口
router.post('/order-users/rate', async (req, res) => {
    try {
        const { orderId, courierId, score } = req.body || {};

        const numericOrderId = Number(orderId);
        const numericScore = Number(score);

        if (!numericOrderId || Number.isNaN(numericOrderId)) {
            return res.status(400).json({ success: false, message: '缺少或非法的订单ID' });
        }

        if (!numericScore || Number.isNaN(numericScore) || numericScore < 1 || numericScore > 5) {
            return res.status(400).json({ success: false, message: '评分必须是1-5之间的数字' });
        }

        // 查找订单，拿到下单者身份ID
        const [orders] = await db.execute(
            'SELECT order_user_id, courier_user_id FROM orders WHERE id = ? LIMIT 1',
            [numericOrderId]
        );

        if (!orders.length) {
            return res.status(404).json({ success: false, message: '订单不存在' });
        }

        const order = orders[0];
        const orderUserId = order.order_user_id;

        if (!orderUserId) {
            return res.status(400).json({ success: false, message: '订单缺少下单者信息，无法评价' });
        }

        // 如果传了courierId，可以在这里做简单校验（例如仅允许参与该订单的代拿员评价）
        if (courierId) {
            const numericCourierId = Number(courierId);
            if (!Number.isNaN(numericCourierId) && order.courier_user_id && Number(order.courier_user_id) !== numericCourierId) {
                return res.status(400).json({ success: false, message: '当前代拿员无权评价该订单' });
            }
        }

        // 简单的信用分调整：以3分为基准，每高/低1分变动5分
        const delta = (numericScore - 3) * 5;

        await db.execute(
            'UPDATE order_users SET credit_score = GREATEST(0, LEAST(100, COALESCE(credit_score, 100) + ?)) WHERE id = ?',
            [delta, orderUserId]
        );

        const [rows] = await db.execute(
            'SELECT LEAST(credit_score, 100) AS credit_score FROM order_users WHERE id = ? LIMIT 1',
            [orderUserId]
        );

        const newScore = rows.length ? rows[0].credit_score : 100;

        res.json({
            success: true,
            message: '评价成功',
            data: { credit_score: newScore }
        });

    } catch (error) {
        console.error('❌ 评价下单者失败:', error);
        res.status(500).json({
            success: false,
            message: '评价失败',
            error: error.message
        });
    }
});

// 更新用户基本信息（支持昵称和头像）
router.put('/:userId', async (req, res) => {
    try {
        const { userId } = req.params;
        const { nickname, avatar_url } = req.body;

        if (!nickname && !avatar_url) {
            return res.json({
                success: false,
                message: '至少需要提供昵称或头像其中一项'
            });
        }

        const updates = [];
        const params = [];

        if (nickname !== undefined) {
            if (typeof nickname !== 'string' || !nickname.trim()) {
                return res.json({
                    success: false,
                    message: '昵称不能为空'
                });
            }

            const trimmedNickname = nickname.trim();
            if (trimmedNickname.length < 2 || trimmedNickname.length > 20) {
                return res.json({
                    success: false,
                    message: '昵称长度必须在2-20个字符之间'
                });
            }

            updates.push('nickname = ?');
            params.push(trimmedNickname);
        }

        if (avatar_url !== undefined) {
            updates.push('avatar_url = ?');
            params.push(avatar_url);
        }

        params.push(userId);

        const [result] = await db.execute(
            `UPDATE users SET ${updates.join(', ')} WHERE id = ?`,
            params
        );

        if (result.affectedRows === 0) {
            return res.json({
                success: false,
                message: '用户不存在或更新失败'
            });
        }

        res.json({
            success: true,
            message: '资料更新成功'
        });

    } catch (error) {
        console.error('❌ 更新用户信息失败:', error);
        res.status(500).json({
            success: false,
            message: '更新用户信息失败'
        });
    }
});

// 确保用户通知设置表存在
async function ensureNotificationTable() {
    await db.execute(`
        CREATE TABLE IF NOT EXISTS user_notification_settings (
            user_id INT PRIMARY KEY,
            enabled TINYINT(1) NOT NULL DEFAULT 1,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )
    `);

    // 兼容已有旧表：如果缺少 enabled 列则补充
    try {
        const [cols] = await db.execute("SHOW COLUMNS FROM user_notification_settings LIKE 'enabled'");
        if (cols.length === 0) {
            await db.execute('ALTER TABLE user_notification_settings ADD COLUMN enabled TINYINT(1) NOT NULL DEFAULT 1');
            console.log('✅ 已为 user_notification_settings 表新增 enabled 列');
        }
    } catch (err) {
        console.warn('⚠️ 检查/新增 user_notification_settings.enabled 失败:', err.message);
    }
}

// 获取用户通知设置
router.get('/:userId/notification-settings', async (req, res) => {
    try {
        const { userId } = req.params;
        await ensureNotificationTable();

        const [rows] = await db.execute(
            'SELECT enabled FROM user_notification_settings WHERE user_id = ? LIMIT 1',
            [userId]
        );

        const enabled = rows.length > 0 ? !!rows[0].enabled : true;

        res.json({
            success: true,
            data: { enabled }
        });
    } catch (error) {
        console.error('❌ 获取通知设置失败:', error);
        res.status(500).json({
            success: false,
            message: '获取通知设置失败'
        });
    }
});

// 更新用户通知设置
router.post('/:userId/notification-settings', async (req, res) => {
    try {
        const { userId } = req.params;
        const { enabled } = req.body;

        await ensureNotificationTable();

        const flag = enabled ? 1 : 0;

        await db.execute(
            'INSERT INTO user_notification_settings (user_id, enabled) VALUES (?, ?) ON DUPLICATE KEY UPDATE enabled = VALUES(enabled)',
            [userId, flag]
        );

        res.json({
            success: true,
            message: '通知设置已更新',
            data: { enabled: !!flag }
        });
    } catch (error) {
        console.error('❌ 更新通知设置失败:', error);
        res.status(500).json({
            success: false,
            message: '更新通知设置失败'
        });
    }
});

// 确保 courier_users 表中存在 service_range 和 service_time 列
async function ensureCourierServiceColumns() {
    try {
        const [cols] = await db.execute('SHOW COLUMNS FROM courier_users');
        const hasRange = cols.some(col => col.Field === 'service_range');
        const hasTime = cols.some(col => col.Field === 'service_time');

        if (!hasRange) {
            await db.execute('ALTER TABLE courier_users ADD COLUMN service_range VARCHAR(255) NULL');
        }

        if (!hasTime) {
            await db.execute('ALTER TABLE courier_users ADD COLUMN service_time VARCHAR(255) NULL');
        }
    } catch (e) {
        console.warn('ensureCourierServiceColumns 失败:', e.message);
    }
}

module.exports = router;